/*
 * Copyright (c) 2021 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.core.transport.session;

import com.inyourcode.core.util.JServiceLoader;
import com.inyourcode.core.transport.session.api.IMessageCoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JackLei
 */
public class MessageCoderFactory {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageCoderFactory.class);
    private static final Map<Byte, IMessageCoder> messageCoderMapping = new HashMap<>();

    static {
        List<IMessageCoder> parserList = JServiceLoader.loadAll(IMessageCoder.class);
        LOGGER.info("Support message coder: {}.", parserList);
        for (IMessageCoder s : parserList) {
            messageCoderMapping.put(s.serializerType(), s);
        }
    }

    public static IMessageCoder getMessageCoder(byte code) {
        IMessageCoder parser = messageCoderMapping.get(code);

        if (parser == null) {
            throw new NullPointerException("unsupported message coder with code: " + code);
        }

        return parser;
    }
}
